// pages/spikeDetaile/spikeDetaile.js
var util = require('../../utils/util.js')
var app = getApp()
Page({
  data: {
    last_update: 0,
    last_x: 0,
    last_y: 0,
    last_z: 0,
    starHideen: false,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    yaoyiyao(this, false)
    getSeckillOne(this, options.id)//获取单个秒杀详情
    this.setData({
      seckillID: options.id,
      agentId: options.agentId
    })
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示   

    var today = util.formatTime(new Date);
    var ago = wx.getStorageSync('countDeta');
    /*----------------统计当天参与活动人数-------------------------- */
    if (wx.getStorageSync('countTimes') == 1) {//判断是够存过次数
      if (today[0] >= ago[0]) {//判断摇过以后是否已经过了一天
        if (today[1] >= ago[1]) {
          if (today[2] > ago[2]) {
            countUserTimes(this);//存次数
          }
        }
      }
    } else {
      countUserTimes(this)//存次数
    }
    /*-------------------------------------------------- */
    if (wx.getStorageSync('determination')) {//如果已经要到过奖，就停止摇一摇
      wx.stopAccelerometer({})//停止重力监听
    }
    hasPrize(this)//判断是否摇过了，如果摇过了则不能摇
    /*-------------------摇一摇的图片动画------------------- */
    var that = this;
    setInterval(function () {
      var animation = wx.createAnimation({
        duration: 150,
        timingFunction: "ease",
      })
      that.animation = animation
      animation.scale(1, 1).top(0).rotate(10).step();
      that.setData({
        animationData: animation.export()
      })
      setTimeout(function () {
        animation.scale(1, 1).top(0).rotate(-10).step();
        that.setData({
          animationData: animation.export()
        })
      }.bind(that), 150)
    }, 300)
    /*-------------------------------------------------- */
  },
  onHide: function () {
    // 页面隐藏
    wx.setStorageSync('ruturnSetTimeout', 1)
    wx.stopAccelerometer({})//停止重力监听
    wx.setStorageSync('countTimes', 1);
    wx.setStorageSync('countDeta', util.formatTime(new Date))//获取年月日
    wx.setStorageSync('setTimeoutsts', 1)
  },
  onUnload: function () {
    // 页面关闭
    wx.setStorageSync('ruturnSetTimeout', 1)
    wx.setStorageSync('countTimes', 1);
    wx.setStorageSync('countDeta', util.formatTime(new Date))//获取年月日
    wx.stopAccelerometer({})//停止重力监听
    wx.setStorageSync('setTimeoutsts', 1)
  },
  // clikss:function(){
  // var that=this;
  //  successPrize(that) 
  // },
})

function getSeckillOne(that, ids) {//请求后台的秒杀详情
  if (ids != "undefined") {
    wx.request({
      url: app.globalData.allUrl + "/YMGW/seckillAction/getSeckillOne",
      data: {
        id: ids,
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
       // console.log(res.data)
        that.setData({
          spikeDetail: res.data.SeckillProduct,
          inventory: parseInt(res.data.SeckillProduct.inventory),
          imgUrl: 'https://www.ymg3.com/ymgImage/seckills/' + res.data.SeckillProduct.productImg,
          startTime:res.data.SeckillProduct.startTime,
          startDate:res.data.SeckillProduct.startDate,
          endTime:res.data.SeckillProduct.endTime,
          deatilImgUrl: 'https://www.ymg3.com/ymgImage/seckills/' + res.data.SeckillProduct.detailImg,
        })
        var startTime=new Date(that.data.startDate+" "+that.data.startTime);
         var endTime=new Date(that.data.startDate+" "+that.data.endTime);
         var startTimes=startTime.getTime();
         var endTimes=endTime.getTime();
         var nowtime=Date.now()
        if (res.data.SeckillProduct.inventory < 1) {//判断数量是否小余1
          wx.stopAccelerometer({})//停止重力监听
          wx.showToast({
            title: "此活动已结束",
            icon: "loading",
            duration: 3000
          })
        }
         var d1 = Date.now();
        // var d2 = new Date(util.formatTime(new Date)[0], parseInt(util.formatTime(new Date)[1]), util.formatTime(new Date)[2], 19, 0, 0);
        var d2 = new Date(that.data.startDate + " " + that.data.startTime)
        var d3 = d2.getTime();
        var total_micro_second = parseInt(d3 - d1);
        that.setData({
          total_micro_seconds: total_micro_second
        })
       // console.log(d2)
        if (d3 - d1 > (60 * 60 * 24 * 1000)) {
          that.setData({
              clock:"今日暂无",
          })
        } else {
           wx.startAccelerometer({  })
           count_down(that);//倒计时
        }
        if(nowtime<startTimes||nowtime>endTimes){//判断是否开始倒计时以及是否结束倒计时了
          wx.stopAccelerometer({})//停止重力监听
        }
      }
    })
  }
}



function yaoyiyao(that, config) {//摇一摇
  var determination = config; //当determination为false时才能摇
  function a() {
    wx.onAccelerometerChange(function (res) {//启用重力感应
      var curTime = new Date().getTime();
      var SHAKE_THRESHOLD = 100;
      var last_update = that.data.last_update;
      // var len = util.res.length;
      // var list = Math.floor(Math.random() * (len - 1))
      if ((curTime - last_update) > 100) {
        var diffTime = curTime - last_update;
        var nums = Math.random() * 30;//要多少次才能中奖
        nums = parseInt(nums, 10);
        var speed = Math.abs(res.x + res.y + res.z - that.data.last_x - that.data.last_y - that.data.last_z) / diffTime * 10000;
        if (speed > SHAKE_THRESHOLD && !determination) {
          wx.playBackgroundAudio({ dataUrl: 'https://www.ymg3.com/ymgVoice/5018.wav', title: 'weixins' })
          // var that = this
          if (nums == "1") {
            wx.stopAccelerometer({})//停止重力监听
            determination = true;//应罗总要求先注释这三行代码
            wx.setStorageSync('determination', true);
            successPrize(that);
          }
        }
        that.setData({
          last_update: curTime,
          last_x: res.x,
          last_y: res.y,
          last_z: res.z
        })
      }
    })
  }
  if (!determination) {
    a()
  }
}

function successPrize(that) {//把获奖者的信息发送给后台，并创建订单
  // console.log(wx.getStorageSync('userid'));
  // console.log(that.data.seckillID)
  wx.request({
    url: app.globalData.allUrl + "/YMGW/seckillAction/createSeckillOrderForm",
    data: {
      userID: wx.getStorageSync('userid'),
      seckillID: that.data.seckillID,
      typeId: 0,
      num: 1
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      if (res.data == 251) {
        wx.stopAccelerometer({})//停止重力监听
        wx.showToast({
          title: "商品已经被抢光啦！",
          icon: "loading",
          duration: 3000
        })
      } else if (res.data == true) {
        wx.stopAccelerometer({})//停止重力监听        
        setTimeout(function () {
          wx.showModal({
            title: '恭喜您中奖了！',
            content: '请点击确认到订单待发货查看奖品',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // determination = true;
                wx.navigateTo({
                  url: '../userOrder/userOrder?id=2',
                })
              }
            }
          })
          wx.playBackgroundAudio({ dataUrl: 'http://fjyd.sc.chinaz.com/files/download/sound1/201410/5012.mp3', title: 'weixin' })
        }, 2000)
      }
    }
  })
}



//倒计时专场

/* 毫秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(that.data.total_micro_seconds)
  });
  if (that.data.total_micro_seconds <= 0) {
    that.setData({
      clock: "已经开抢",
      starHideen: true
    });
     yaoyiyao(this, false)
    // wx.setStorageSync('determination', false)//开启摇一摇功能
    // timeout则跳出递归
    return;
  }


  setTimeout(function () {
    // 放在最后--
    that.data.total_micro_seconds -= 1000;
    that.setData({
      total_micro_seconds: that.data.total_micro_seconds
    })
    count_down(that);
  }, 1000)
  // if (wx.getStorageSync('setTimeoutsts') == 1) {
  //   clearTimeout(sts)
  // }
}
// 时间格式化输出，如03:25:19 。每1000ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return hr + ":" + min + ":" + sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}




function countUserTimes(that) {//统计秒杀人数
  //console.log(wx.getStorageSync("agentid"))
  wx.request({
    url: app.globalData.allUrl + "/YMGW/seckillAction/bodyCount",
    data: {
      agentId: that.data.agentId,
      seckillId: that.data.seckillID
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
    }
  })
}


function hasPrize(that) {
  wx.request({
    url: app.globalData.allUrl + "/YMGW/seckillAction/getSeckillOrderForm",
    data: {
      userID: wx.getStorageSync('userid'),
      productId: that.data.seckillID
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      // console.log(res.data)
      if (res.data == false) {
        wx.stopAccelerometer({})//停止重力监听
        wx.showToast({
          title: "您已中奖，请前往我的-待收货页面查看",
          icon: "loading"
        })
      }
    }
  })
}